import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/tpa/Home.vue';
import Login from '../views/Login.vue';
import DataEntry from '../views/tpa/DataEntry.vue';
import DataView from '../views/tpa/DataView.vue';
import DataEdit from '../views/tpa/DataEdit.vue';
import DataExport from '../views/tpa/DataExport.vue';
import NavBar from '../views/NavBar.vue';
import DataList from '../views/tpa/DataList.vue';
import SearchPage from '@/views/deepseekSearch/SearchPage.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    redirect: '/login', // 默认重定向到登录页
  },
  {
    path: '/login',
    component: Login,
  },
  {
    path: '/tpa',
    component: NavBar, // 将 NavBar 作为父组件
    children: [
      {
        path: 'home', // 子路由路径：/tpa/home
        name: 'tpa首页',
        meta: { title: 'tpa首页' },
        component: Home,
      },
      {
        path: 'data-entry', // 子路由路径：/tpa/data-entry
        component: DataEntry,
      },
      {
        path: 'data-view', // 子路由路径：/tpa/data-view
        component: DataView,
      },
      {
        path: '/tpa/data-list', // 数据列表页
        name: 'DataList',
        component: DataList,
      },
      {
        path: '/tpa/data-edit/:id', // 数据编辑页，动态路由
        name: 'DataEdit',
        component: DataEdit,
      },
      {
        path: 'data-export', // 子路由路径：/tpa/data-export
        component: DataExport,
      },
    ],
  },
  {
    path: '/ds',
    component: NavBar, // 将 NavBar 作为父组件
    children: [
      {
        path: 'deepseekSearch', // 子路由路径：
        name: 'ds搜索',
        meta: { title: 'ds搜索' },
        component: SearchPage,
      },
    ]
    // ... 其他路由配置
  },
];

const router = new VueRouter({
  routes,
  mode: 'history',
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = !!localStorage.getItem('token'); // 判断用户是否已登录

  if (to.path === '/login') {
    // 如果用户访问登录页且已登录，则跳转到首页
    if (isLoggedIn) {
      next('/tpa/home');
    } else {
      next();
    }
  } else if (to.path.startsWith('/tpa')) {
    // 如果用户访问 /tpa 下的页面且未登录，则跳转到登录页
    if (!isLoggedIn) {
      next('/login');
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
